<template>
  <div class="page-container">
    <list-searcher v-model:searchForm="queryParam" :search-list="searchList" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #index="{ rowIndex }"> {{ rowIndex + 1 }}</template>
      <!-- 业务细信息 -->
      <template #businessInfo="{ record }">
        {{ record.useTypeName }}
        <br />
        {{ record.refCode }}
        <br />
        <!-- 渠道信息 -->
        <div v-if="record.refChannelType !== null">
          渠道：<span :class="'bg-' + record.refChannelType" class="common-bg">{{ record.refChannelTypeName }}</span>
          <br />
          {{ record.refCodeChannel || '-' }}
        </div>
        <!-- 操作人操作时间 -->
        <div v-if="record.refOperateUserName">
          {{ record.refOperateUserName || '-' }}
        </div>
        <div v-if="record.refOperateTime">
          {{ record.refOperateTime || '-' }}
        </div>
      </template>
      <template #cycle="{ record }">
        {{ record.fromTime && record.toTime ? record.statusName + '：' + record.fromTime + ' 至 ' + record.toTime : '-' }}
      </template>

      <template #status="{ record }">
        <div v-if="record.sourceSyncStatus != 0">
          <status-tag :value="record.sourceSyncStatus" :label="record.sourceSyncStatusName" type="inventorySyncStatus" />
        </div>

        <div v-if="record.sourceSyncStatus == 0">
          <status-tag :value="record.sourceSyncStatus" :label="record.sourceSyncStatusName" type="inventorySyncStatus" />
          <a-popover>
            <a-button class="case-btn" type="outline">原因</a-button>
            <template #content>
              <p>{{ '原因：' + (record.sourceErrorMsg || '-') }}</p>
            </template>
          </a-popover>
        </div>
      </template>
      <template #time="{ record }">
        <div v-if="record.sourceChannelStoreList && record.sourceChannelStoreList.length">
          <span class="border-none td" v-for="(item, i) in record.sourceChannelStoreList" :key="i">{{ item }}</span>
        </div>
        <div v-else>
          <span>{{ '-' }}</span>
        </div>
      </template>
    </table-index>
  </div>
</template>

<script setup name="InventorySyncList">
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getList } from '@/api/business/channelSyncStore'

  import { onMounted, reactive, computed } from 'vue'
  import { usePageDict, useSysDict } from '@/hooks/useDict'
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'

  const channelSyncStoreDict = usePageDict('channelSyncStoreDict')
  const sysDict = useSysDict(['short_order_channel_type'])
  const route = useRoute()
  const { query } = route

  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input', maxlength: 10 },
      {
        label: '业务单号',
        prop: 'refCodeLike',
        type: 'a-input',
        maxlength: 50,
        placeholder: '请输入业务单号/临时占用ID',
      },
      {
        label: '服务类型',
        prop: 'useType',
        type: 'a-select',
        options: channelSyncStoreDict.CarUseTypeEnum,
      },
      {
        label: '同步状态',
        prop: 'syncStatus',
        type: 'a-select',
        options: channelSyncStoreDict.syncStatusEnum,
      },
      {
        label: '同步类型',
        prop: 'status',
        type: 'a-select',
        options: channelSyncStoreDict.statusEnum,
      },
      {
        label: '订单来源',
        prop: 'refOrderSource',
        type: 'a-select',
        options: channelSyncStoreDict.orderSourceEnum,
      },
      {
        label: '订单渠道',
        prop: 'refChannelType',
        type: 'a-select',
        options: sysDict.short_order_channel_type,
      },
      {
        label: '占用目标渠道',
        prop: 'sourceId',
        type: 'a-select',
        options: channelSyncStoreDict.thirdpartySourceEnum,
      },
      {
        label: '目标运营主体',
        prop: 'accountId',
        type: 'remote-select',
        attrs: { type: 'target_channel_account' },
      },
      {
        label: '操作人',
        prop: 'refOperateUserId',
        type: 'remote-select',
        attrs: { type: 'staff_operator' },
      },
      {
        label: '库存开始时间',
        prop: 'startDate',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.fromTimeStart = value[0]
          queryParam.fromTimeEnd = value[1]
        },
      },
      {
        label: '库存结束时间',
        prop: 'endDate',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.toTimeStart = value[0]
          queryParam.toTimeEnd = value[1]
        },
      },
      {
        label: '任务结束时间',
        prop: 'endTaskTime',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.endTimeStart = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
    ]
  })

  // table 配置
  const table = useTable({
    columns: [
      { title: '车牌号', width: 110, dataIndex: 'licenseNo', fixed: 'left' },
      { title: '服务类型', width: 100, dataIndex: 'userTypeName' },
      { title: '业务单信息', width: 200, slotName: 'businessInfo' },
      { title: '库存周期', width: 340, slotName: 'cycle' },
      // width 不要修改，height、line-height有问题
      { title: '同步对象', dataIndex: 'sourceNameAndSubject', width: 200 },
      { title: '同步状态', slotName: 'status', width: 180 },
      { title: '渠道的库存占用周期', slotName: 'time', width: 300 },
      { title: '任务开始时间', width: 190, dataIndex: 'sourceStartTime' },
      { title: '任务结束时间', width: 190, dataIndex: 'sourceEndTime' },
    ],
    spanMethod: (data) => {
      const { record, column } = data

      // 定义需要合并的列
      const mergeColumns = ['车牌号', '服务类型', '业务单信息', '库存周期']
      // 判断当前列是否需要合并
      const shouldMerge = mergeColumns.indexOf(column.title) !== -1
      // 如果不需要合并，返回默认的单元格设置
      if (!shouldMerge) {
        return { rowspan: 1, colspan: 1 }
      }
      // 合并
      if (record.rowspan) {
        return { rowspan: record.rowspan, colspan: 1 }
      }
      // 对于同组的其他行，隐藏单元格
      return { rowspan: 0, colspan: 0 }
    },
    buttons: [],
    bordered: {
      wrapper: true,
      cell: true,
    },
  })
  // 接口参数
  const queryParam = reactive({})

  // 列表接口调用
  const loadData = (page) => {
    const fn = useFetchTableDataApi(table, queryParam, getList)
    fn(page).then((res) => {
      const { data } = res
      table.dataList = data.flatMap((list) => {
        if (!list.sourceList?.length) {
          return list
        }
        return list.sourceList.map((item, index) => ({
          ...list,
          sourceNameAndSubject: `${item.sourceName}-${item.subject}`,
          sourceStartTime: item.startTime,
          sourceEndTime: item.endTime,
          sourceSyncStatus: item.syncStatus,
          sourceSyncStatusName: item.syncStatusName,
          sourceErrorMsg: item.errorMsg,
          sourceChannelStoreList: item.channelStoreList,
          rowspan: index === 0 ? list.sourceList.length : 0,
        }))
      })
    })
  }

  // mounted 调用接口
  onMounted(() => {
    if (query.sourceId && query.accountId && query.syncStatus && query.endTime) {
      queryParam.sourceId = +query.sourceId
      queryParam.accountId = query.accountId
      queryParam.syncStatus = +query.syncStatus
      queryParam.endTimeEnd = dayjs(query.endTime).format('YYYY-MM-DD HH:mm:ss')
      queryParam.endTaskTime = [dayjs(query.endTime).format('YYYY-MM-DD HH:mm:ss'), dayjs(query.endTime).format('YYYY-MM-DD HH:mm:ss')]
      loadData()
    } else {
      loadData()
    }
  })
</script>

<style lang="less" scoped>
  .channel-card {
    :deep(.arco-card-body) {
      padding: 0px 0px 20px !important;
    }
  }
  .common-bg {
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    font-size: 12px;
    font-weight: 500;
    color: #ffffff;
    padding: 0 8px;
    background: #ff9c5f;
  }
  .bg {
    &--1 {
      background: #ffe180;
    }
    &-2 {
      background: #f68b8b;
    }
    &-3 {
      background: #80e2ff;
    }
    &-1 {
      background: #00b2ff;
    }
    &--3 {
      background: #56e2a8;
    }
    &--4 {
      background: #76c204;
    }
  }
  .color {
    &-0 {
      color: #f53f3f;
    }
    &-2 {
      color: #ff7d00;
    }
    &-1 {
      color: #00b42a;
    }
  }
  .td {
    display: inline-block;
    width: 100%;
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    padding: 10px 0;
    &::before {
      content: '';
      display: block;
      position: absolute;
      left: -12px;
      right: -12px;
      bottom: 0;
      height: 0.5px;
      background-color: #e5e6eb;
    }
  }
  .td-bottom {
    &::before {
      content: '';
      display: block;
      position: absolute;
      left: -16px;
      right: -16px;
      bottom: 0;
      height: 0.5px;
      background-color: #e5e6eb;
    }
  }
  .padding-top-0 {
    padding-top: 0;
  }
  .padding-bottom-0 {
    padding-bottom: 0;
  }
  .border-none {
    &::before {
      content: none !important;
    }
  }

  .case-btn {
    width: 40px;
    height: 20px;
    font-size: 12px;
    margin-left: 8px;
  }
  .text-ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
  }
</style>
